<template>
  <n-spin :show="state.showLoading" class="spin" stroke="#c04851">
    <div class="lottery" v-if="state.lottery">
      <h2>{{ state.lottery.name }}</h2>
      <p class="spec">{{ state.lottery.spec }}</p>
      <div class="pool">
        <span>奖池：</span>
        <span>{{ state.lottery.pool }}</span>
      </div>
      <div class="end">
        <span>截至日期：{{ state.lottery.end_at.replace('T', ' ') }}</span>
      </div>
      <div v-if="state.lottery.state === 1 && state.key && !state.prize" class="gamer">
        <div class="input">
          <n-input
            v-model:value="state.name"
            :autofocus="true"
            maxlength="7"
            type="text"
            placeholder="请输入你的昵称"
          />
        </div>
        <n-button class="fetch" type="success" ghost @click="showModal = true">抽取</n-button>
      </div>
      <div v-else-if="state.prize" class="prize">恭喜你获得：{{ state.prize.name }}</div>
    </div>
    <div v-else class="empty">
      <n-empty description="没有此抽奖"></n-empty>
    </div>
  </n-spin>
  <n-modal
    v-model:show="showModal"
    preset="dialog"
    type="warning"
    title="确认抽取吗？"
    positive-text="确认"
    @positive-click="onConfirm"
    negative-text="取消"
  />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage, NButton, NModal, NSpin, NEmpty, NInput } from 'naive-ui'
import axios from 'axios'
import moment from 'moment'
import { ApiPrefix } from '../../config.js'

const showModal = ref(false)
const state = reactive({
  showLoading: false,
  lottery: null,
  prize: null,
  name: null,
  key: null,
})

const route = useRoute()
const message = useMessage()

const checkLocalPrize = (lotteryId, expiredAt) => {
  const prize = JSON.parse(localStorage.getItem('prize'))
  if (prize && moment(expiredAt).isBefore(moment())) {
    localStorage.removeItem('prize')
  }
  if (prize && lotteryId === parseInt(prize.lottery_id)) {
    state.prize = prize
  }
}

const getLottery = (lotteryId) => {
  axios.post(`${ApiPrefix}/lottery/get`, {
    id: lotteryId
  }).then((r) => {
    if (r.data) {
      state.lottery = r.data
      checkLocalPrize(lotteryId, r.data.end_at)
    }
  }).catch((e) => {
    console.log(e)
    message.error('获取失败，请检查网络或稍后再试')
  })
}

const getErrorMsg = (msg) => {
  switch (msg) {
    case 'IpExist':
      return '该地址已参与过抽奖'
    case 'NameExist':
      return '该昵称已参与过抽奖'
    case 'NameRequired':
      return '需要填写昵称'
    case 'NoPrize':
      return '奖池已空'
    case 'LotteryInvalid':
      return '非法抽奖'
    case 'LotteryNotFound':
      return '未找到该抽奖'
    default:
      return '未知错误'
  }
}

const onConfirm = () => {
  state.showLoading = true
  if (!state.name || !state.name.replace(/ /g, '')) {
    state.showLoading = false
    message.error('请输入你的游戏昵称')
    return
  }
  if (!state.lottery || !state.key) {
    state.showLoading = false
    message.error('未知状态')
    return
  }
  if (state.lottery && state.lottery.state === 1 && state.key && state.name) {
    setTimeout(() => {
      axios.post(`${ApiPrefix}/prize/fetch`, {
        lottery_id: state.lottery.id,
        key: state.key,
        name: state.name
      }).then((r) => {
        if (r.data) {
          message.success(`恭喜！抽得${r.data.prize.name}`)
          state.prize = r.data.prize
          const localData = {
            lottery_id: state.lottery.id,
            expire_at: state.lottery.end_at,
            fetch_at: r.data.prize.fetch_at,
            prize_id: r.data.prize.id,
            name: r.data.prize.name,
            gamer_key: r.data.gamer.key,
            gamer_name: r.data.gamer.name
          }
          // console.log(localData)
          localStorage.setItem('prize', JSON.stringify(localData))
        }
      }).catch((e) => {
        const detail = e?.response?.data?.detail
        if (detail)  message.error(`抽奖失败，${getErrorMsg(detail)}`)
        else message.error('抽奖失败，请检查网络或稍后再试')
      }).finally(() => {
        state.showLoading = false
      })
    }, 1000)
  }
}

const checkKey = (id, key) => {
  axios.post(`${ApiPrefix}/lottery/check`, {
    id: id,
    key: key
  }).then((r) => {
    if (r.data) {
      state.key = r.data
    }
  })
}

onMounted(() => {
  const lotteryId = route.params.id
  const key = route.params.key
  if (lotteryId) {
    getLottery(parseInt(lotteryId))
    if (key) checkKey(parseInt(lotteryId), key)
  }
})
</script>

<style scoped>
.spin {
  width: 100%;
}
.lottery {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  width: 100%;
}
.gamer {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.fetch {
  margin: 20px 0;
  width: 200px;
}
.end,
.input {
  margin-top: 10px;
}
.prize {
  font-weight: bold;
  margin-top: 10px;
  color: #ed5a65;
}
.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 200px;
}
</style>
